<template>
  <el-dialog title="报价测算" class="dialog" @closed="handlerCancel" :model-value="true" width="1100px" center>
    <el-form ref="formRef" :model="form" label-width="90px" :rules="rules">
      <el-row>
        <el-col :span="7">
          <el-form-item label="利润率" prop="profit">
            <el-input v-model="form.profit">
              <template #append>%</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="运输方式" prop="transportTypes">
            <el-select placeholder="请选择" multiple v-model="form.transportTypes" clearable>
              <el-option label="快递" value="express" />
              <el-option label="空运" value="air" />
              <el-option label="海运" value="sea" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="运费模板" prop="freightTemplateId">
            <el-select placeholder="请选择" v-model="form.freightTemplateId" clearable>
              <el-option v-for="temp in tempList" :label="temp.templateName" :value="temp.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="line_con">
      <div class="line"></div>
      测算结果
      <div class="line"></div>
    </div>
    <el-table :span-method="arraySpanMethod" :data="tableData" element-loading-svg-view-box="0, 0, 1024, 1024" :element-loading-svg="LoadingSvg" border style="width: 100%" v-loading="loading">
      <el-table-column prop="count" label="数量" />
      <el-table-column prop="transportTypes" width="90" label="发货渠道" />
      <el-table-column prop="netPrice" width="90" label="netPrice" />
      <el-table-column prop="orderPrice" width="120" label="订单金额" />
      <el-table-column prop="costPrice" width="120" label="工厂成本" />
      <el-table-column prop="delivery" label="交期" />
      <el-table-column prop="freight" width="190" label="运费" />
      <el-table-column prop="profit" width="120" label="订单利润" />
    </el-table>
    <div class="style_row" v-if="tableData && tableData.length">
      <el-select v-model="viewStyle" class="style_select mr20">
        <el-option value="1" label="样式一" />
      </el-select>
      <div class="mr20">
        <span class="mr10">表格文字颜色</span>
        <el-color-picker @change="changeEmailCon" v-model="textColor" />
      </div>
      <div>
        <span class="mr10">表格文字背景颜色</span>
        <el-color-picker @change="changeEmailCon" v-model="bgColor" />
      </div>
    </div>
    <div class="mt20" v-html="emailCon" />
    <template #footer>
      <div class="dialog-footer">
        <el-button size="small" @click="handlerCancel">取消</el-button>
        <el-button size="small" type="primary" @click="handlerCount">
            计算
        </el-button>
        <el-button  v-if="tableData && tableData.length" size="small" type="primary" @click="handlerApplyEmail">应用到邮件</el-button>
      </div>
    </template>
  </el-dialog>
</template>
    
<script lang="ts" setup>
  import { defineProps, ref, onMounted } from 'vue';
  import api from '/@/api/email/index';
  import { FormRules } from 'element-plus';
  import { getEmailContent } from './utils';
  import { useTempCache } from '/@/stores/tempCache';
  import pinia from '/@/stores/index';
  import { useRoute, useRouter } from 'vue-router';
  import { LoadingSvg } from '/@/utils/loading';

  const props = defineProps({
    offerId: {
      type: [String, Number],
      default: ''
    },
  });

  const route = useRoute();
  const router = useRouter();
  const formRef = ref();
  const viewStyle = ref('1');
  const emailCon = ref('');
  const offerData = ref<any>({});
  const textColor = ref('#fff');
  const bgColor = ref('#409EFF');
  const tempCache = useTempCache(pinia);
  const tempList: any = ref([]);
  const rules = ref<FormRules>({
    profit: [
      { required: true, message: '请输入', trigger: 'blur' },
    ],
    transportTypes: [
      { required: true, message: '请选择', trigger: 'change' },
    ],
  });

  const form = ref<any>({
    profit: '20',
    transportTypes: ['express', 'air', 'sea']
  });
  
  const emit = defineEmits(['close']);
  const tableData = ref([]);
  let priceOriginData: any = []
  const loading = ref(false);

  const handlerCancel = () => {
    emit('close');
  };

  const arraySpanMethod = ({
    row,
    column,
    rowIndex,
    columnIndex,
  }: any) => {
    if (row.groupNum && columnIndex === 0) {
      return [row.groupNum, 1];
    } else {
      if (columnIndex === 0) {
        return [0, 0];
      }
    }
  };

  const handlerApplyEmail = () => {
    let title = 'Quotation for ';
    const { productCode, clientEmail, clientName } = route.query;
    if (productCode) {
      title = title + '#' + productCode + ' ';
    }
    
    if (offerData.value.productName) {
      title = title + offerData.value.productName;
    }
    tempCache.setData({
      type: 'writeEmail',
      toEmail: clientEmail,
      toEmailName: clientName,
      content: emailCon.value,
      title
    });
    sessionStorage.setItem('openWriteDialog', '1')
    router.push('/home');
  };

  const handlerCount = async () => {
    if (!formRef.value) {
      return;
    }

    try {
      loading.value = true;
      await formRef.value.validate();
      const res = await api.offer.showPrice({
        ...form.value,
        inquiryOfferId: props.offerId,
        transportTypes: form.value.transportTypes.join(',')
      });
      if (res.code === 200) {
        priceOriginData = JSON.parse(JSON.stringify(res.data))
        const list = res.data.reduce((allList: any[], item: any) => {
          const arr = item.itemList.map((obj: any) => {
            return {
              ...obj,
              delivery: obj.delivery.replace('天', 'Days'),
              count: item.count
            }
          });
          arr[0].groupNum = arr.length;
          allList.push(...arr);
          return allList;
        }, []);
        tableData.value = list;
        changeEmailCon();
      } 
    } catch {}
    loading.value = false;
  };

  const changeEmailCon = () => {
    if (!tableData.value.length) {
      return;
    }
    const config = { 
      tableBg: bgColor.value,
      tableColor: textColor.value
    }
    emailCon.value = getEmailContent(offerData.value, priceOriginData, form.value.transportTypes, config);
  };

  const init = async () => {
    const res = await api.offer.getDetail(props.offerId);
    if (res.code === 200) {
      offerData.value = res.data;
      offerData.value.productCode = route.query.productCode;
    }
  };


  const getTempList = async () => {
    const res = await api.offer.getFeTempList();
    if (res.code === 200) {
      tempList.value = res.data;
    }
  };

  onMounted(() => {
    init()
    getTempList()
  });
  
  </script>
  <style lang="scss" scoped>

  .line_con {
    margin: 10px 0;
    display: flex;
    align-items: center;

    .line {
      border-top: 1px solid #ddd;
      flex: 1;
      margin: 0 5px;
    }
  }

  .style_row {
    display: flex;
    margin-top: 20px;
  }

  .style_select {
    width: 140px;
  }
  </style>